package cl.whyem.spring.integration.mail.app;

import cl.whyem.spring.integration.mail.service.DesuscripcionMailService;
import java.util.concurrent.CountDownLatch;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.Message;
import org.springframework.integration.MessageHandlingException;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageHandler;
import org.springframework.stereotype.Component;

@Component("procesadorMail")
public class ProcesadorMail extends Thread {

    private final static Logger logger = LoggerFactory.getLogger(ProcesadorMail.class);

    @Autowired
    @Qualifier("desuscripcionMailService")
    private DesuscripcionMailService desuscripcionMailService;

    @Autowired
    @Qualifier("receiveChannel")
    private DirectChannel receiveChannel;

    @Qualifier("countDownLatch")
    private CountDownLatch countDownLatch;

    @Override
    public void run() {
        try {
            handleMails();
            //@todo: suscribe inicia su propio thread....
            //seguir probando Thread.join ...etcetc...
        } catch (Exception ex) {
            logger.error("" + ex);
        } finally {
            countDownLatch.countDown();
        }
    }

    public void handleMails() {
        receiveChannel.subscribe(new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                Object payload = message.getPayload();
                if (payload instanceof MimeMessage) {
                    try {
                        MimeMessage mm = (MimeMessage) payload;
                        logger.debug("Subject -> {}", mm.getSubject());
                        String from = mm.getFrom() == null ? null : ((InternetAddress) mm.getFrom()[0]).getAddress();
                        logger.debug("From -> {}", from);
                        String to = mm.getRecipients(RecipientType.TO) == null ? null : ((InternetAddress) mm.getRecipients(RecipientType.TO)[0]).getAddress();
                        logger.debug("To -> {}", to);
                    } catch (javax.mail.MessagingException ex) {
                        logger.error("" + ex);
                    }
                } else {
                    logger.debug("Error");
                    throw new MessageHandlingException(message, "Unable to create MailMessage from payload type ["
                            + message.getPayload().getClass().getName() + "], expected MimeMessage, MailMessage, byte array or String.");
                }
                logger.debug("loopeando...");
            }
        });
    }

}
